package com.ruoyi.web.controller.system;

import java.io.PrintWriter;
import java.util.Date;
import java.util.List;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.weixin.po.AccessUser;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.system.domain.WxSendMsgModel;
import com.ruoyi.web.controller.common.CommonController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.base.AjaxResult;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.weixin.WeixinUtil;
import com.ruoyi.common.utils.weixin.po.AccessToken;
import com.ruoyi.framework.web.base.BaseController;
import com.ruoyi.system.domain.WxCode;
import com.ruoyi.system.domain.WxUser;
import com.ruoyi.system.service.IWeixinService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 微信用户模块管理
 * @author admin
 *
 */
@Controller
@RequestMapping("/system/wxTemplates")
@Api(tags = "微信群发模板管理")
public class WxTemplatesController extends BaseController{

	private static final Logger log = LoggerFactory.getLogger(WxTemplatesController.class);

	private String prefix = "system/wxtemplates";
	
	@Autowired
	private IWeixinService weixinService;
	
	/**
	 * 视图页面展示（群发）
	 * @return
	 */
	@RequiresPermissions("system:wxTemplates:view")
    @GetMapping()
    public String index(ModelMap mmap){
		// 获取微信号列表
		mmap.put("codes", weixinService.selectWxCodes());
		// 获取模板列表
		mmap.put("templates", weixinService.selectWxSendMsgModels());
        return prefix + "/templates";
    }

	@GetMapping("/sendMsg")
	public String sendMsg(ModelMap mmap,HttpServletRequest request){

		String codeId = request.getParameter("wxId");
		if(StringUtils.isNotEmpty(codeId)){
			// 获取微信号
			WxCode code = weixinService.getEntityById(Long.valueOf(codeId));
			mmap.put("code", code);
			// 获取模板列表
			mmap.put("templates", weixinService.selectWxSendMsgModels());

		}
		return prefix + "/send_templates";
	}

	/**
	 * 模板管理
	 * @return
	 */
	@RequiresPermissions("system:wxTemplates:index:view")
	@GetMapping("/index")
	public String index(){
		return prefix + "/templatesmanager";
	}

	/**
	 * 模板列表页数据
	 * @param wxSendMsgModel
	 * @return
	 */
	@ApiOperation(value = "模板列表页数据",notes = "可分页")
	@ApiImplicitParam(name = "WxSendMsgModel" ,value = "查询对象实体")
	@RequiresPermissions("system:wxTemplates:list")
	@PostMapping("/list")
	//@RequestMapping(value = "/list",method = RequestMethod.POST)
	@ResponseBody
	public TableDataInfo list(WxSendMsgModel wxSendMsgModel){
		startPage();
		List<WxSendMsgModel> list = weixinService.selectWxSendMsgModelList(wxSendMsgModel);
		return getDataTable(list);
	}



	/**
	 * 添加微信模板
	 * @return
	 */
	@GetMapping("/add")
	public String add(){
		return prefix + "/add";
	}

	/**
	 * 新增保存微信号
	 */
	@RequiresPermissions("system:wxTemplates:add")
	@Log(title = "微信模板管理", businessType = BusinessType.INSERT)
	@PostMapping("/add")
	@Transactional(rollbackFor = Exception.class)
	@ResponseBody
	public AjaxResult addSave(WxSendMsgModel wxSendMsgModel){
		wxSendMsgModel.setCreateAt(new Date());
		return toAjax(weixinService.insertWxSendMsgModel(wxSendMsgModel));
	}

	/**
	 * 获取模板对象
	 * @param modelId
	 * @param response
	 * @throws Exception
	 */
	@PostMapping("/getwxTemplateById")
	public void getwxTemplateById(String modelId, HttpServletResponse response) throws Exception{
		WxSendMsgModel wxSendMsgModel = weixinService.getwxTemplateById(Long.valueOf(modelId));
		response.setCharacterEncoding("utf-8");
		response.getWriter().write(JSONObject.toJSONString(wxSendMsgModel));
	}


	@RequiresPermissions("system:wxTemplates:remove")
	@Log(title = "微信模板管理", businessType = BusinessType.DELETE)
	@PostMapping("/remove")
	@ResponseBody
	public AjaxResult remove(String ids){
		try{
			return toAjax(weixinService.deleteWxSendMsgModelByIds(ids));
		} catch (Exception e){ return error(e.getMessage()); }
	}

	/**
	 * 修改模板
	 */
	@GetMapping("/edit/{id}")
	public String edit(@PathVariable("id") Long id, ModelMap mmap){
		mmap.put("wxSendMsgModel", weixinService.getwxTemplateById(id));
		return prefix + "/edit";
	}

	/**
	 * 修改保存模板
	 */
	@RequiresPermissions("system:wxTemplates:edit")
	@Log(title = "微信模板管理", businessType = BusinessType.UPDATE)
	@PostMapping("/edit")
	@Transactional(rollbackFor = Exception.class)
	@ResponseBody
	public AjaxResult editSave(WxSendMsgModel wxSendMsgModel){
		return toAjax(weixinService.updateWxSendMsgModel(wxSendMsgModel));
	}

	/**
     * 群发短信
     */
    @PostMapping("/groupSending")
    @ResponseBody
    public AjaxResult groupSending(int type,String wxCode,String jsonStr){
        return toAjax(weixinService.groupSending(type,wxCode,jsonStr,"模板群发"));
    }
	
}
